#!/bin/bash

set -e

cd /wg/
if [ ! -f "privatekey" ] ; then
    umask 077
    wg genkey | tee privatekey | wg pubkey > publickey
fi


if [ ! -f "wg0.conf" ] ; then
private=$(cat privatekey)
cat  >  /wg/wg0.conf <<EOF
[Interface]
Address = $ADDR
SaveConfig = true
PostUp = iptables -A FORWARD -i %i -j ACCEPT; iptables -A FORWARD -o %i -j ACCEPT; iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
PostDown = iptables -D FORWARD -i %i -j ACCEPT; iptables -D FORWARD -o %i -j ACCEPT; iptables -t nat -D POSTROUTING -o eth0 -j MASQUERADE
PrivateKey = $private
EOF
fi

[[ -n "$LISTENPORT" ]] &&  echo  "ListenPort = $LISTENPORT" >> /wg/wg0.conf

if [[  -n "$ENDPOINT"  ||   -n "$PUBLICKEY"  ||  -n "$ALLOWDIP" ]]  ; then 
cat  >>  /wg/wg0.conf <<EOF
[Peer]
PublicKey = $PUBLICKEY
AllowedIPs = $ALLOWDIP
Endpoint = $ENDPOINT
PersistentKeepalive = 25
EOF

fi

function route() {
    if [ -f "route.txt" ] ; then
        for i in $(cat route.txt) ; do
            [[ -z "$(ip route |grep $( echo $i | awk -F "," '{print $1}'))" ]] && ip route add $( echo $i | awk -F "," '{print $1}') via $( echo $i | awk -F "," '{print $2}')
        done
    fi
}


while true ; do
    if [  ! -n "$(wg)" ] ; then
        echo `date "+%Y-%m-%d %H:%M:%S" `  重新拉起vpn进程
        wg-quick up /wg/wg0.conf && route
    fi
    sleep 150
done